<template>
  <!-- 
    一旦添加transition组件，但内部元素显示隐藏时，会自动添加一些类名

      显示 -> 隐藏
        .dialog-leave
        .dialog-leave-active
        .dialog-leave-to

          遮罩层: 透明度 1 -> 0
          内容区: transform: translateY() 0 -> -100px

      隐藏 -> 显示
        .dialog-enter
        .dialog-enter-active
        .dialog-enter-to

          遮罩层: 透明度 0 -> 1
          内容区: transform: translateY()  -100px -> 0
   -->
  <transition name="dialog">
    <div class="dialog" v-show="visible">
      <!-- 遮罩层 -->
      <div class="dialog-mask" @click="close"></div>
      <!-- 内容区 -->
      <div class="dialog-wrap" :style="{ width }">
        <!-- 头部 -->
        <div class="dialog-header">
          <div class="dialog-title">{{ title }}</div>
          <div class="dialog-close" @click="close">X</div>
        </div>
        <!-- 内容区 -->
        <div class="dialog-content">
          <!-- 显示默认插槽的内容 -->
          <slot />
        </div>
        <!-- 底部 -->
        <div class="dialog-footer">
          <!-- 显示具名插槽的内容 -->
          <slot name="footer" />
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: "SDialog",
  props: {
    title: {
      type: String,
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    width: {
      type: String,
      default: "50%",
    },
  },
  methods: {
    close() {
      this.$emit("update:visible", false);
    },
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          // 禁用滚动条
          document.documentElement.style.overflow = "hidden";
          return;
        }
        // 不禁用
        document.documentElement.style.overflow = "auto";
      },
      immediate: true,
    },
  },
  beforeDestroy() {
    document.documentElement.style.overflow = "auto";
  },
};
</script>

<style lang="less" scoped>
.dialog {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 99;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: -1;
}

.dialog-wrap {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
}

.dialog-title {
  font-size: 18px;
}

.dialog-close {
  font-size: 14px;
  color: #999;
  cursor: pointer;
  &:hover {
    color: red;
  }
}

.dialog-content {
  padding: 20px 0;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
